package com.luyue.zagj.activity.home;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.luyue.zagj.R;
import com.luyue.zagj.utils.ToastUtil;
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;
import com.tianditu.android.maps.OnGetPoiResultListener;
import com.tianditu.android.maps.PoiInfo;
import com.tianditu.android.maps.PoiSearch;
import com.tianditu.android.maps.PoiSearch.CityInfo;
import com.tianditu.android.maps.PoiSearch.ProvinceInfo;
import com.tianditu.android.maps.TErrorCode;
import com.tianditu.android.maps.TGeoAddress;
import com.tianditu.android.maps.TGeoDecode;
import com.tianditu.android.maps.overlay.MarkerOverlay;
import com.tianditu.android.maps.overlayutil.PoisOverlay;

/**
 * 代码示例-关键字搜索
 */
public class LocationActivity extends Activity implements OnGetPoiResultListener , TGeoDecode.OnGeoResultListener,OnClickListener {
    private static final int DIALOG_TYPE_LIST = 1;
    private static final int DIALOG_POI_LIST = 2;
    private static final int DIALOG_CITY_LIST = 3;

    private final static String TYPE_NAME[] = { "普通搜索", "视野内搜索", "周边搜索", "在北京搜索" };

    private MapView mMapView;

    private Button mBtnType;
    private EditText mEditKey;
    private Button mBtnSearch;

    private Button mBtnList;
    private Button mBtnPre;
    private Button mBtnNext;

    private TextView mTextTips;

    // 搜索条件
    private String mKeyword;
    private int mSearchType = 0;
    // 搜索类
    private PoiSearch mPoiSearch;
    // 搜索结果
    private ArrayList<PoiInfo> mPoiList;
    private ArrayList<ProvinceInfo> mCityList;
    // 覆盖物
    private PoisOverlay mPoisOverlay;

    private String longitude;//经度
    private String latitude;//纬度
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.poisearch_activity);

        mMapView = (MapView) findViewById(R.id.mapview);
        mMapView.setBuiltInZoomControls(true);

        SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
        longitude = sp.getString("longitude", "");
        latitude = sp.getString("latitude", "");
        GeoPoint geoPoint = new GeoPoint((int) ( Double.valueOf(latitude) * 1E6), (int) ( Double.valueOf(longitude) * 1E6));
        searchGeoDecode(geoPoint);
        //120.165366,30.298465
        // type
        mBtnType = (Button) findViewById(R.id.buttonType);
        mBtnType.setOnClickListener(this);

        // edit
        mEditKey = (EditText) findViewById(R.id.editKey);
        mEditKey.setText("餐饮");

        // search
        mBtnSearch = (Button) findViewById(R.id.buttonSearch);
        mBtnSearch.setOnClickListener(this);

        // list
        mBtnList = (Button) findViewById(R.id.buttonList);
        mBtnList.setOnClickListener(this);
        mBtnList.setEnabled(false);


        // 关键词搜索
        mBtnPre = (Button) findViewById(R.id.buttonPre);
        mBtnPre.setOnClickListener(this);

        // 附近搜索
        mBtnNext = (Button) findViewById(R.id.buttonNext);
        mBtnNext.setOnClickListener(this);
        mTextTips = (TextView) findViewById(R.id.textViewTips);
        mTextTips.setText("");

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.buttonType:
                break;
            case R.id.buttonSearch:
                String key = mEditKey.getText().toString();
                searchKey(key, mSearchType);
                break;
            case R.id.buttonList:
                if (mPoiList != null && mPoiList.size() != 0) {
                    removeDialog(DIALOG_POI_LIST);
                    showDialog(DIALOG_POI_LIST);
                } else if (mCityList != null && mCityList.size() != 0) {
                    removeDialog(DIALOG_CITY_LIST);
                    showDialog(DIALOG_CITY_LIST);
                }
                break;
            case R.id.buttonPre:
                mSearchType=0;
                mBtnNext.setBackgroundResource(R.color.white);
                mBtnNext.setTextColor(Color.BLUE);
                mBtnPre.setBackgroundResource(R.color.light_bule2);
                mBtnPre.setTextColor(Color.WHITE);
                break;
            case R.id.buttonNext:
                mSearchType=1;
                mBtnPre.setBackgroundResource(R.color.white);
                mBtnPre.setTextColor(Color.BLUE);
                mBtnNext.setBackgroundResource(R.color.light_bule2);
                mBtnNext.setTextColor(Color.WHITE);
                break;
        }
    }

    /* 得到的坐标实际位置
    * @param geoPoint 位置
    */
    private GeoPoint mGeoPoint;
    private TGeoDecode mGeoDecode;
    private void searchGeoDecode(GeoPoint geoPoint) {
        mGeoPoint = geoPoint;

        // mMapView.getController().setMapBound(mGeoPoint, 11);

        // 开始搜索
        if (mGeoDecode == null)
            mGeoDecode = new TGeoDecode(this);
        mGeoDecode.search(geoPoint);
    }
    private void searchKey(String key, int type) {
        mKeyword = key;
        mTextTips.setText("开始搜索 key = " + key + ", type = " + type);
        mBtnList.setEnabled(false);
        mBtnPre.setEnabled(false);
        mBtnNext.setEnabled(false);

        if (mPoisOverlay != null) {
            mMapView.removeOverlay(mPoisOverlay);
            mPoisOverlay = null;
        }

        switch (type) {
            case 0: // 普通
                mPoiSearch = new PoiSearch(this, this, mMapView);
                mPoiSearch.search(key, null, null);
                break;
            case 1: // 视图范围内
                GeoPoint p1 = mMapView.getProjection().fromPixels(0, 0);
                GeoPoint p2 = mMapView.getProjection().fromPixels(mMapView.getWidth(),
                        mMapView.getHeight());
                mPoiSearch = new PoiSearch(this, this, mMapView);
                mPoiSearch.search(key, p1, p2);
                break;
            case 2: // 周边
                mPoiSearch = new PoiSearch(this, this, mMapView);
                GeoPoint center = mMapView.getMapCenter();
                mPoiSearch.search(key, center, 2000);
                break;
            case 3: // 行政区
                mPoiSearch = new PoiSearch(this, this, mMapView);
                mPoiSearch.search("156110000", key);
                break;
        }

    }

    @Override
    public void OnGetPoiResult(ArrayList<PoiInfo> poiInfo, ArrayList<ProvinceInfo> cityInfo,
                               String keyword, int error) {
        mPoiList = poiInfo;
        mCityList = cityInfo;

        int poiSize = poiInfo != null ? poiInfo.size() : 0;
        int citySize = cityInfo != null ? cityInfo.size() : 0;

        if (error != TErrorCode.OK) {
            mTextTips.setText("搜索关键字失败 key = " + mKeyword + ", type = " + mSearchType
                    + ", error = " + error);
            return;
        }
        if (poiSize == 0 && citySize == 0) {
            mTextTips.setText("没有找到结果 key = " + mKeyword + ", type = " + mSearchType);
            return;
        }

        String tips = String.format(Locale.getDefault(),
                "搜索关键字结果 key =%s, type = %s, poiSize = %s, citySize = %s", mKeyword,
                TYPE_NAME[mSearchType], poiSize, citySize);
        mTextTips.setText(tips);
        mBtnList.setEnabled(true);
        if (poiSize > 0) {
            mBtnPre.setEnabled(true);
            mBtnNext.setEnabled(true);
        }

        // 添加覆盖物

        Drawable marker = getResources().getDrawable(R.drawable.poi_xml);
        mPoisOverlay = new PoisOverlay(marker);
        mPoisOverlay.setData(poiInfo);
        mPoisOverlay.setDrawFocusedItem(true);
        mPoisOverlay.showFocusAlways(true);
        mPoisOverlay.populate();
        mMapView.addOverlay(mPoisOverlay);
        if (poiInfo==null){
            ToastUtil.getToast("未找到该位置",this);
            return;
        }
        GeoPoint point = poiInfo.get(0).mPoint;
        mMapView.getController().animateTo(point);
        if (mPoiList != null && mPoiList.size() != 0) {
            removeDialog(DIALOG_POI_LIST);
            showDialog(DIALOG_POI_LIST);
        } else if (mCityList != null && mCityList.size() != 0) {
            removeDialog(DIALOG_CITY_LIST);
            showDialog(DIALOG_CITY_LIST);
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_TYPE_LIST:
                return showTypeList();
            case DIALOG_POI_LIST:
                return showPoiList();
            case DIALOG_CITY_LIST:
                return showCityList();
            default:
                break;
        }
        return null;
    }

    private Dialog showTypeList() {
        DialogInterface.OnClickListener listenerList = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                mSearchType = which;
            }
        };

        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                mBtnType.setText(TYPE_NAME[mSearchType]);
            }
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择搜索方式");
        builder.setSingleChoiceItems(TYPE_NAME, mSearchType, listenerList);
        builder.setPositiveButton("确定", listener);
        return builder.create();
    }

    private Dialog showPoiList() {
        int size = mPoiList.size();
        final String items[] = new String[size];
        for (int i = 0; i < size; ++i) {
            items[i] = "地址 :" + mPoiList.get(i).mStrAdd ;

        }
        DialogInterface.OnClickListener listenerList = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                GeoPoint geoPoint = mPoisOverlay.getItem(which).getPoint();
                mPoisOverlay.setFocusID(which);
                mMapView.getController().setCenter(geoPoint);
                Intent intent=new Intent();
                intent.putExtra("loseAddress",items[which].substring(4));
                getSharedPreferences("config",MODE_PRIVATE).edit().putString("loseAddress",items[which].substring(4)).commit();
                setResult(1,intent);
                finish();
                dialog.dismiss();
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("POI结果");
        builder.setItems(items, listenerList);
        return builder.create();
    }

    String mDlgCityTitle = "";
    List<CityInfo> mDlgCityList = null;

    private Dialog showCityList() {
        int size = mDlgCityList != null ? mDlgCityList.size() : 0;
        final String items[] = new String[size];
        for (int i = 0; i < size; ++i) {
            items[i] = mDlgCityList.get(i).mStrName;
        }
        DialogInterface.OnClickListener listenerList = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                GeoPoint geoPoint = mPoisOverlay.getItem(which).getPoint();
                mPoisOverlay.setFocusID(which);
                mMapView.getController().setCenter(geoPoint);
                Intent intent=new Intent();
                intent.putExtra("loseAddress",items[which]);
                setResult(1,intent);
                finish();
                dialog.dismiss();

            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(mDlgCityTitle);
        builder.setItems(items, listenerList);
        return builder.create();

    }

    @Override
    public void onGeoDecodeResult(TGeoAddress addr, int i) {
        MarkerOverlay mOverlay = new MarkerOverlay();
        mOverlay.setPosition(mGeoPoint);
        mMapView.getController().setZoom(15);  InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView()
                    .getWindowToken(), 0);
        }

        //mMapView.getController().setMapBound(mGeoPoint, 11);
        String str = "当前位置:" + addr.getFullName() + "\n";
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        MyLocationOverlay mLocation = new MyLocationOverlay(this, mMapView);
        mLocation.enableMyLocation();
        mMapView.getController().setCenter(mLocation.getMyLocation());
        mMapView.addOverlay(mLocation);

        mOverlay = new MarkerOverlay();
        mMapView.addOverlay(mOverlay);
    }


}
